package top.lyjwn.ajui.widget.image;

import android.animation.ValueAnimator;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.DataSource;
import com.bumptech.glide.load.engine.GlideException;
import com.bumptech.glide.load.resource.bitmap.RoundedCorners;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.RequestListener;
import com.bumptech.glide.request.target.Target;
import com.xuexiang.xui.widget.imageview.preview.PreviewBuilder;
import com.xuexiang.xui.widget.layout.XUILinearLayout;

import org.jetbrains.annotations.NotNull;

import java.util.ArrayList;
import java.util.List;

import androidx.annotation.Nullable;
import top.lyjwn.ajui.R;
import top.lyjwn.ajui.util.ImageUtil;
import top.lyjwn.ajui.util.RoundUtil;
import top.lyjwn.ajui.widget.loading.LoadingView;

/**
 * 网络图片视图
 *
 * @author luoyujie
 */
public class NetImageView extends LinearLayout {

    private Context context;

    private ImageView widget_net_image_view_image;

    private LoadingView widget_net_image_view_loading;

    private boolean isLoadAnim = true;

    private int shapeType = 0;

    public NetImageView(Context context) {
        this(context, null);
    }

    public NetImageView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.imageView);
        isLoadAnim = ta.getBoolean(R.styleable.imageView_isLoadAnim, true);
        shapeType = ta.getInt(R.styleable.imageView_shapeType, 0);
        init();
    }


    private void init() {
        View v = LayoutInflater.from(context).inflate(R.layout.widget_net_image_view, this);
        widget_net_image_view_image = v.findViewById(R.id.widget_net_image_view_image);
        widget_net_image_view_loading = v.findViewById(R.id.widget_net_image_view_loading);

    }

    /**
     * 加载图片
     *
     * @param url
     * @param ll
     */
    public void load(String url, LoadListener ll) {
        if (isLoadAnim) {
            widget_net_image_view_image.setImageAlpha(0);
            widget_net_image_view_loading.start();
        }
        final ValueAnimator va_undo = ValueAnimator.ofInt(0, 255);
        va_undo.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int a = (int) animation.getAnimatedValue();
                widget_net_image_view_image.setImageAlpha(a);
            }
        });
        va_undo.setDuration(300);
        //
        RequestBuilder<Drawable> glide = Glide.with(context)
                .load(url)
//                .placeholder(R.drawable.rotate_pro)
                .error(R.drawable.unable_to_load_image)
                .timeout(10 * 1000)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        widget_net_image_view_image.setImageResource(R.drawable.unable_to_load_image);
                        if (isLoadAnim) {
                            widget_net_image_view_loading.stop();
                            va_undo.start();
                        } else {
                            widget_net_image_view_image.setImageAlpha(255);
                        }
                        ll.fail(e);
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (isLoadAnim) {
                            widget_net_image_view_loading.stop();
                            va_undo.start();
                        } else {
                            widget_net_image_view_image.setImageAlpha(255);
                        }
                        if (ll != null) {
                            Bitmap bitmap = ImageUtil.drawableToBitmap(resource);
                            ll.coming(bitmap);
                        }
                        return false;
                    }
                });
//        glide.transform(new RoundedCorners(40));//圆角
//        glide.sizeMultiplier(0.5f)//如果原图过大那么使用这个
//        if (isLoadAnim){
//            glide.transition(new DrawableTransitionOptions().crossFade(300));//渐显效果
//        }
        switch (shapeType) {
            case 1:
                glide.circleCrop();//圆形
                break;
        }

        glide.into(widget_net_image_view_image);
    }

    /**
     * 加载
     *
     * @param url
     */
    public void load(String url) {
        load(url, null);
    }

    /**
     * 加载
     *
     * @param bitmap
     */
    public void load(Bitmap bitmap) {
        if (isLoadAnim) {
            widget_net_image_view_image.setImageAlpha(0);
        }
        final ValueAnimator va_undo = ValueAnimator.ofInt(0, 255);
        va_undo.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int a = (int) animation.getAnimatedValue();
                widget_net_image_view_image.setImageAlpha(a);
            }
        });
        va_undo.setDuration(300);
        RequestBuilder<Drawable> glide = Glide.with(context)
                .load(bitmap)
                .placeholder(R.drawable.rotate_pro)
                .error(R.drawable.unable_to_load_image)
                .listener(new RequestListener<Drawable>() {
                    @Override
                    public boolean onLoadFailed(@Nullable GlideException e, Object model, Target<Drawable> target, boolean isFirstResource) {
                        widget_net_image_view_image.setImageResource(R.drawable.unable_to_load_image);
                        if (isLoadAnim) {
                            va_undo.start();
                        } else {
                            widget_net_image_view_image.setImageAlpha(255);
                        }
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(Drawable resource, Object model, Target<Drawable> target, DataSource dataSource, boolean isFirstResource) {
                        if (isLoadAnim) {
                            va_undo.start();
                        } else {
                            widget_net_image_view_image.setImageAlpha(255);
                        }
                        return false;
                    }
                });
        switch (shapeType) {
            case 1:
                glide.circleCrop();//圆形
                break;
        }
        glide.into(widget_net_image_view_image);
    }

    /**
     * 预览的图片
     *
     * @param urls
     */
    public void preview(@NotNull final String... urls) {
        final List<ImageInfo> imageInfos = new ArrayList<>();
        for (String url : urls) {
            ImageInfo imageInfo = new ImageInfo();
            imageInfo.setUrl(url);
            imageInfos.add(imageInfo);
        }
        widget_net_image_view_image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageInfos.size() > 1) {
                    PreviewBuilder.from((Activity) context)
                            .setImgs(imageInfos) //图片对象集合
                            .setCurrentIndex(0) //当前预览的索引
                            .setSingleFling(true)
                            .setType(PreviewBuilder.IndicatorType.Number) //指示器为数字
                            .setProgressColor(R.color.colorPrimary)
                            .setFullscreen(true)
                            .start();
                } else {
                    PreviewBuilder.from((Activity) context)
                            .setImg(imageInfos.get(0)) //图片对象集合
                            .setCurrentIndex(0) //当前预览的索引
                            .setSingleFling(true)
                            .setType(PreviewBuilder.IndicatorType.Number) //指示器为数字
                            .setProgressColor(R.color.colorPrimary)
                            .setFullscreen(true)
                            .start();
                }

            }
        });
    }

    /**
     * 预览的图片
     *
     * @param urls
     * @param index
     */
    public void preview(List<String> urls, final int index) {
        final List<ImageInfo> imageInfos = new ArrayList<>();
        for (String url : urls) {
            ImageInfo imageInfo = new ImageInfo();
            imageInfo.setUrl(url);
            imageInfos.add(imageInfo);
        }

        widget_net_image_view_image.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (imageInfos.size() > 1) {
                    PreviewBuilder.from((Activity) context)
                            .setImgs(imageInfos) //图片对象集合
                            .setCurrentIndex(index) //当前预览的索引
                            .setSingleFling(true)
                            .setType(PreviewBuilder.IndicatorType.Number) //指示器为数字
                            .setProgressColor(R.color.colorPrimary)
                            .setFullscreen(true)
                            .start();
                } else {
                    PreviewBuilder.from((Activity) context)
                            .setImg(imageInfos.get(0)) //图片对象集合
                            .setCurrentIndex(0) //当前预览的索引
                            .setSingleFling(true)
                            .setType(PreviewBuilder.IndicatorType.Number) //指示器为数字
                            .setProgressColor(R.color.colorPrimary)
                            .setFullscreen(true)
                            .start();
                }

            }
        });
    }

    public ImageView getImageView() {
        return widget_net_image_view_image;
    }


    public interface LoadListener {
        void coming(Bitmap bitmap);

        void fail(GlideException e);
    }

}
